package com.wlcb.jpower.chat.controller.wx.mp;

import com.wlcb.jpower.module.base.enums.JpowerError;
import com.wlcb.jpower.module.base.exception.JpowerAssert;
import com.wlcb.jpower.module.base.vo.ResponseData;
import com.wlcb.jpower.module.common.controller.BaseController;
import com.wlcb.jpower.module.common.utils.ReturnJsonUtil;
import com.wlcb.jpower.utils.WxMpInstance;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.SneakyThrows;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author: liwenfei
 * @version: v1.0
 * @time: 2021/4/22 10:30
 * @desc: 微信网页授权
 */
@Api(tags = "微信网页授权")
@RestController
@RequestMapping("auth")
public class WxMpAuthController extends BaseController {

    @ApiOperation("获取用户openid")
    @RequestMapping("getOpenid")
    @SneakyThrows(WxErrorException.class)
    public ResponseData<WxOAuth2AccessToken> getOpenid(@ApiParam("公众号ID") String appId,@ApiParam("公众号code") String code) {

        JpowerAssert.notEmpty(appId, JpowerError.Arg,"公众号ID不可为空");
        JpowerAssert.notEmpty(code, JpowerError.Arg,"公众号code不可为空");

        WxMpService wxMpService = WxMpInstance.getWxMp().switchoverTo(appId);
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        return ReturnJsonUtil.ok("操作成功", accessToken);
    }
}
